package com.cnxjs.shs4et.controller;

import com.cnxjs.shs4et.common.Result;
import com.cnxjs.shs4et.entity.Topic;
import com.cnxjs.shs4et.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/topic")
public class TopicController {

    @Autowired
    private TopicService topicService;

    // 分页查询所有帖子
    @GetMapping("/")
    public Result findAll(@RequestParam(defaultValue= "0") Integer page,
                          @RequestParam(defaultValue= "20") Integer size,
                          @RequestParam(defaultValue = "publishTime") String sortRule){
        Sort sort = Sort.by(Sort.Direction.DESC, sortRule);
        Pageable pageable = PageRequest.of(page, size, sort);
        return topicService.findAll(pageable);
    }

    // 按照具体板块分页查所有帖子
    @GetMapping("/block")
    public Result findByBlock(@RequestParam(defaultValue= "0") Integer page,
                                @RequestParam(defaultValue= "20") Integer size,
                                @RequestParam(defaultValue = "publishTime") String sortRule,
                                @RequestParam Integer forum) {
        Sort sort = Sort.by(Sort.Direction.DESC, sortRule);
        Pageable pageable = PageRequest.of(page, size, sort);
        return topicService.findByBlock(pageable, forum);
    }

    // 按照论坛查所有帖子，尝试自己实现
    @GetMapping("/forum")
    public Result findByForum(@RequestParam(defaultValue= "0") Integer page,
                              @RequestParam(defaultValue= "20") Integer size,
                              @RequestParam(defaultValue = "publishTime") String sortRule,
                              @RequestParam String forumName) {
        return topicService.findByForum(page, size, sortRule, forumName);
    }

    // 按照标题模糊查询帖子
    @GetMapping("/title")
    public Result findByTitle(@RequestParam(defaultValue= "0") Integer page,
                              @RequestParam(defaultValue= "20") Integer size,
                              @RequestParam(defaultValue = "publishTime") String sortRule,
                              @RequestParam String title) {
        Sort sort = Sort.by(Sort.Direction.DESC, sortRule);
        Pageable pageable = PageRequest.of(page, size, sort);
        return topicService.findByTitle(pageable, "%"+title+"%");
    }

    // 发帖子
    @PostMapping("/add")
    public Result add(@RequestBody Topic topic) {
        return topicService.add(topic);
    }

    // 更新帖子
    @PostMapping("/update")
    public Result update(@RequestBody Topic topic) {
        return topicService.update(topic);
    }

    // 伪删除（锁定）帖子
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        return topicService.delete(id);
    }
}
